//
//  CLGloble.m
//  chanlin
//
//  Created by Ryan on 14-11-1.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLGloble.h"
#import "AppDelegate.h"
#import "IFTieMessageView.h"
#import <CoreText/CoreText.h>
#import "SgrReachability.h"
#import "CLBaseViewController.h"
#import <CommonCrypto/CommonDigest.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#import "IFMoviePlayerController.h"
#import "SgrGCD.h"
#import "ChangyanSDK.h"
#import "CLSlidersViewController.h"
#import "CLDocViewController.h"
#import "CLTopicViewController.h"
#import "CLVideoViewController.h"
#import "CLSubViewController.h"
#import "ClEntityHead.h"
#import "CLPushAnimatedRight.h"
#import "CLLiveViewController.h"

@implementation CLGloble

SGR_DEF_SINGLETION(CLGloble)

@synthesize lastestRelease = _lastestRelease;
- (instancetype)init{
    self=[super init];
    if(self){
        self.magazineName=@"QS Showcase";
        self.magazineId=@"1";
        //5277
        self.urls=@{@"list":@"http://appv2.chanlin.org/e/app/list.php?cid=%@&page=%d",
                    @"slider":@"http://appv2.chanlin.org/e/app/news.php?id=%@",
                    @"login":@"http://appv2.chanlin.org/e/opclient/user.php",
                    @"topic":@"http://appv2.chanlin.org/e/app/topic.php?ztid=%@",
                    @"userEdit":@"http://appv2.chanlin.org/e/app/user_edit.php"};
        self.menus=@{
                     
                     @"13":@{@"channelId":@"13",@"channelName":@"头条",@"tpl":@"0"
                                  ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=13"},
//                    @"13":@{@"channelId":@"13",@"channelName":@"头条",@"tpl":@"0"
//                                                               ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=168"},
                     @"9":@{@"channelId":@"9",@"channelName":@"禅林卫视",@"tpl":@"0"
                                 ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=9"},
                     @"2":@{@"channelId":@"2",@"channelName":@"海潮音",@"tpl":@"0"
                                     ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=2"},
                     @"7":@{@"channelId":@"7",@"channelName":@"思想界",@"tpl":@"0"
                                     ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=7"},
                     @"10":@{@"channelId":@"10",@"channelName":@"时评",@"tpl":@"0"
                                  ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=10"},
                     @"1":@{@"channelId":@"1",@"channelName":@"法讯",@"tpl":@"0"
                                ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=1"},
                     @"14":@{@"channelId":@"14",@"channelName":@"媒体",@"tpl":@"1"
                              ,@"url":@"http://appv2.chanlin.org/e/app/clist.php?cid=14"},
                     @"102":@{@"channelId":@"102",@"channelName":@"世界观",@"tpl":@"0"
                                     ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=102"},
//                     @"8":@{@"channelId":@"8",@"channelName":@"禅修",@"tpl":@"0"
//                                  ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=8"},
                      @"104":@{@"channelId":@"104",@"channelName":@"高僧传",@"tpl":@"0"
                                        ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=104"},
                     @"61":@{@"channelId":@"61",@"channelName":@"微信",@"tpl":@"2"
                                 ,@"url":@"http://appv2.chanlin.org/e/app/clist.php?cid=61"},
                     @"60":@{@"channelId":@"60",@"channelName":@"微博",@"tpl":@"2"
                                ,@"url":@"http://appv2.chanlin.org/e/app/clist.php?cid=60"},
                     @"110":@{@"channelId":@"110",@"channelName":@"禅宗语录",@"tpl":@"0"
                                   ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=110"},
                     @"103":@{@"channelId":@"103",@"channelName":@"禅匠诗书",@"tpl":@"0"
                                      ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=103"},
                     @"4":@{@"channelId":@"4",@"channelName":@"人文",@"tpl":@"0"
                                 ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=4"},
                     @"3":@{@"channelId":@"3",@"channelName":@"佛艺",@"tpl":@"0"
                               ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=3"},
                     @"12":@{@"channelId":@"12",@"channelName":@"论文",@"tpl":@"0"
                                 ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=12"},
                     @"109":@{@"channelId":@"109",@"channelName":@"老年佛学院",@"tpl":@"0"
                                           ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=109"},
                     @"6":@{@"channelId":@"6",@"channelName":@"读书",@"tpl":@"0"
                                ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=6"},
                     @"11":@{@"channelId":@"11",@"channelName":@"公开课",@"tpl":@"0"
                                    ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=11"},
                     @"98":@{@"channelId":@"98",@"channelName":@"素食",@"tpl":@"0"
                                ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=98"},
                      @"5":@{@"channelId":@"5",@"channelName":@"法物流通",@"tpl":@"0"
                                ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=5"},
                     @"167":@{@"channelId":@"167",@"channelName":@"画报",@"tpl":@"0"
                              ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=167"},
                     @"8":@{@"channelId":@"8",@"channelName":@"今日禅说",@"tpl":@"0"
                              ,@"url":@"http://appv2.chanlin.org/e/app/list_v2.php?cid=8"}
                     
                     };
        self.keyOrder= @[@"13",@"9",@"8",@"2",@"7",@"10",@"1",@"109",@"103",@"167",@"104",@"102",@"3",@"110",@"4",
                         @"8",@"98",@"6",@"11",@"12",@"61",@"60",
                         @"14",@"5"];
       // [[NSUserDefaults standardUserDefaults] setObject:menus forKey:menus_dic];
        NSDictionary *menus=[[NSUserDefaults standardUserDefaults] dictionaryForKey:menus_dic];
        if(menus){
            self.menus=menus;
        }
        NSArray *keyOrder=[[NSUserDefaults standardUserDefaults] arrayForKey:menus_order];
        if(keyOrder){
            self.keyOrder=keyOrder;
        }
        
        self.defaultOrderMenuItems=@[@"13",@"9",@"8",@"2",@"7",@"10",@"1",@"109",@"103",@"167"];
        
        self.topciIcon=[UIImage imageNamed:@"list_topic_indentfir.png"];
        self.slideIcon=[UIImage imageNamed:@"icon_slide.png"];
        self.videoIcon=[UIImage imageNamed:@"icon_video.png"];
        self.audioIcon=[UIImage imageNamed:@"icon_audio.png"];
        self.liveIcon=[UIImage imageNamed:@"list_live_indentfir.png"];
        self.levelIcons=@[@"groupId_1.png",@"groupId_2.png",@"groupId_3.png"];
        
        self.change=@{@"toutiao":@"13",
                      @"weishi":@"9",
                      @"haichaoyin":@"2",
                      @"sixiangjie":@"7",
                      @"gongkaike":@"11",
                      @"chanxiu":@"8",
                      @"faxun":@"1",
                      @"foyi":@"3",
                      @"renwen":@"4",
                      @"dushu":@"6",
                      @"lunwen":@"12",
                      @"rss":@"14",
                      @"fawu":@"5",
                      @"weixin":@"61",
                      @"weibo":@"60",
                      @"shiping":@"10",
                      @"sushi":@"98",
                      @"shijieguan":@"102",
                      @"jiangshishu":@"103",
                      @"gaosengzhuan":@"104",
                      @"laonianfoxueyuan":@"109",
                      @"zongyulu":@"110"};

//        _lastestRelease = YES;//网络不好，或未知时，认为是最新版
        self.formatter=[[NSDateFormatter alloc] init];
        self.formatter.dateFormat=@"HH:mm";
        
        self.supports=[[NSMutableSet alloc] init];
        NSArray *set1 =[[NSUserDefaults standardUserDefaults] arrayForKey:@"livesupport"];
      
        if(set1){
            [self.supports addObjectsFromArray:set1];
        }
        
    }
    return self;
}


- (NSString *)objChange:(NSString *)oldKey{
    return [self.change sgrGetStringForKey:oldKey];
}

- (void)reflash{
    NSDictionary *menus=[[NSUserDefaults standardUserDefaults] dictionaryForKey:menus_dic];
    if(menus){
        self.menus=menus;
    }
    NSArray *keyOrder=[[NSUserDefaults standardUserDefaults] arrayForKey:menus_order];
    if(keyOrder){
        self.keyOrder=keyOrder;
    }

}

- (NSArray *)allKeys{
    return self.keyOrder;
}

- (void)clearMovie{
    if([CLGloble sharedInstance].singleMovie){
        [[CLGloble sharedInstance].singleMovie stop];
        [[CLGloble sharedInstance].singleMovie.view removeFromSuperview];
        [CLGloble sharedInstance].singleMovie=nil;
    }
}

- (void)setUser:(CLUser *)user{
    _user=user;
    if(user==nil){
        [CLUser clear];
    }else{
        [user save];
    }
    
    
}



- (void)didChangeToInterfaceOrientationPortrait
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

- (BOOL)systemScreen_4
{
    if (self.globleHeight == 568.0) {
        return YES;
    }
    else
        return NO;
}

- (BOOL)isLogin{
    return _isStrNotNull(self.user.uid);
}

- (NSString *)md5:(NSString *)seed{
    if (_isStrNULL(seed)) return @"null";
    const char *str = [seed UTF8String];
    if(!str) return @"null";
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *md5String = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                           r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    return md5String;
}

- (UIImage *)getTodyLogo{
    NSTimeInterval last=[[NSUserDefaults standardUserDefaults] doubleForKey:@"getTodyLogo_time"];
    NSString *lastLogo=[[NSUserDefaults standardUserDefaults] stringForKey:@"lastLogo"];
    if( _isStrNULL(lastLogo)  || (fabs([[NSDate date] timeIntervalSince1970]-last))>(3600*24)){
        int index=(arc4random()%4)+1;
        NSString *key=[NSString stringWithFormat:@"index_logo%d.png",index];
        UIImage *img=[UIImage imageNamed:key];
        [[NSUserDefaults standardUserDefaults] setObject:key forKey:@"lastLogo"];
        [[NSUserDefaults standardUserDefaults] setDouble:last forKey:@"getTodyLogo_time"];
        return img?img:[UIImage imageNamed:@"index_logo4.png"];
    }else{
        return [UIImage imageNamed:lastLogo];
    }
}

- (UIWindow *)getMainWindow{
    return ((AppDelegate *)[UIApplication sharedApplication].delegate).window;
}

- (BOOL)systemVersionAtLeastIOS8
{
    return [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0;
  
}

- (void)showTieAlertMessage:(NSString *)message subMessage:(NSString *)subMessage{
    IFTieMessageView *view=[[IFTieMessageView alloc] initWith:IFTieMessageViewStyleAlert
                                                      message:message
                                                   subMessage:subMessage];
    [view show];
}

- (void)showTieSuccessMessage:(NSString *)message subMessage:(NSString *)subMessage{
    IFTieMessageView *view=[[IFTieMessageView alloc] initWith:IFTieMessageViewStyleSuccess
                                                      message:message
                                                   subMessage:subMessage];
    [view show];
    
}

- (void)showTieUnCollectMessage:(NSString *)message subMessage:(NSString *)subMessage{
    IFTieMessageView *view=[[IFTieMessageView alloc] initWith:IFTieMessageViewStyleCancelCollect
                                                      message:message
                                                   subMessage:subMessage];
    
    [view show];
    
}

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message block:(void(^)(int buttonIndex))block cancelButtonTitle:(NSString *)cancelButtonTitle button1:(NSString *)button1 button2:(NSString *)button2{
    [[self k_currentController] _showAlertWithTitle:title message:message block:block cancelButtonTitle:cancelButtonTitle button1:button1 button2:button2];
}

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message block:(void(^)(int buttonIndex))block cancelButtonTitle:(NSString *)cancelButtonTitle confirmButtonTitles:(NSString *)confirmButtonTitles{
    [[self k_currentController] _showAlertWithTitle:title message:message block:block cancelButtonTitle:cancelButtonTitle confirmButtonTitles:confirmButtonTitles];
}

- (BOOL)checkAnimationLock:(NSObject *)lock{
    if(self.dispatchLock==nil){
        self.dispatchLock=lock;
        return YES;
    }
    return self.dispatchLock==lock;
}

- (void)cleanAnimationLock{
    self.dispatchLock=nil;
}

- (NSString *)stringFromJson:(NSObject *)obj{
    NSData *jsonData = nil;
    if ([NSJSONSerialization isValidJSONObject:obj])
        jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
    
    if (jsonData) {
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return nil;
}

- (NSObject *)jsonFromString:(NSString *)str{
    return [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
                                           options:NSJSONReadingMutableContainers
                                             error:nil];
}

- (BOOL)checkOnLine{
    SgrReachability *reachability=[SgrReachability reachabilityForInternetConnection];
    SgrNetworkStatus status= [reachability currentReachabilityStatus];
    return !(status==kSgrNotReachable);
}

-(NSString *)appVersion {
    NSString *v=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSArray *arr=[v componentsSeparatedByString:@"."];
    if([arr count]>3){
        NSRange range=[v rangeOfString:@"." options:NSBackwardsSearch];
        NSRange range1;
        range1.location=0;
        range1.length=range.location;
        v=[v substringWithRange:range1];
    }
    return v;
}

- (void)setUserHelpShowStatu:(BOOL)complete
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:complete forKey:[NSString stringWithFormat:@"%@%@",KeyOfUserHelpShow,[self appVersion]]];
}

- (BOOL)isUserHelpShowComplete
{
    BOOL isComplete = [[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"%@%@",KeyOfUserHelpShow,[self appVersion]]];
    return isComplete ;
}


- (void)doPush:(int) type docId:(NSString *)did{
    if(type==CLList_sliders){
        CLSlidersViewController *slider=[CLSlidersViewController new];
        slider.itemId=did;
        [[CLPushAnimatedRight sharedInstance] pushController:slider];
        
    }else if(type==CLList_doc){
        CLDocViewController *doc=[CLDocViewController new];
        doc.itemId=did;
        [[CLPushAnimatedRight sharedInstance] pushController:doc];
        
    }else if(type==CLList_topic){
        CLTopicViewController *topic=[CLTopicViewController new];
        topic.itemId=did;
        [[CLPushAnimatedRight sharedInstance] pushController:topic];
    }else if(type==CLList_video){
        CLVideoViewController *video=[CLVideoViewController new];
        video.itemId=did;
       [[CLPushAnimatedRight sharedInstance] pushController:video];
        
    }else if(type==CLList_sub){
        CLSubViewController *sub=[CLSubViewController new];
        sub.itemId=did;
        //sub.title=@"";
        [[CLPushAnimatedRight sharedInstance] pushController:sub];
    }else if(type==CLList_audio){
        CLDocViewController *doc=[CLDocViewController new];
        doc.itemId=did;
        [[CLPushAnimatedRight sharedInstance] pushController:doc];
    } if(type==CLList_live){
        CLLiveViewController *live=[CLLiveViewController new];
        
        live.itemId=did;
        [[CLPushAnimatedRight sharedInstance] pushController:live];
        return;
        
        
    }

}

- (CLBaseViewController *)currentController{
   
    UINavigationController *naiv=(UINavigationController *)([self getMainWindow].rootViewController);
    if([naiv.topViewController isKindOfClass:[CLBaseViewController class]]){
        return (CLBaseViewController *)(naiv.topViewController);
    }else{
        return nil;
    }
}

- (CGSize)calculateSizeWithFont:(UIFont *)font
                       withText:(NSString *)text
                    withMaxSize:(CGSize)maxSize
                  withLineSpace:(float)lineSpace
                withAllowIndent:(BOOL)allowIndent
{
    if(!font)
        return CGSizeZero;
    if(_isStrNULL(text))
        return CGSizeZero;
    
    //字体
    CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef) font.fontName, font.pointSize, NULL);
    //行高
    float _lineHeight = lineSpace;
    CTParagraphStyleSetting lineSpaceSetting;
    lineSpaceSetting.spec = kCTParagraphStyleSpecifierLineSpacing;
    lineSpaceSetting.value = &_lineHeight;
    lineSpaceSetting.valueSize = sizeof(CGFloat);
    
    //对其方式
    CTParagraphStyleSetting alignmentStyleSetting;
    CTTextAlignment alignment = kCTJustifiedTextAlignment;
    alignmentStyleSetting.spec=kCTParagraphStyleSpecifierAlignment;
    alignmentStyleSetting.valueSize=sizeof(alignment);
    alignmentStyleSetting.value=&alignment;
    
    CGFloat leading = font.lineHeight -font.ascender + font.descender;
    CTParagraphStyleSetting leadSetting;
    leadSetting.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
    leadSetting.value = &leading;
    leadSetting.valueSize = sizeof(float);
    
    CTParagraphStyleRef paragraphStyle;
    if (allowIndent) {
        // 首行缩进
        CTParagraphStyleSetting fristline;
        CGFloat fristlineindent = 2.0f*(font.pointSize)+1;
        fristline.spec = kCTParagraphStyleSpecifierFirstLineHeadIndent;
        fristline.value = &fristlineindent;
        fristline.valueSize = sizeof(float);
        CTParagraphStyleSetting paragraphSettings[4] = {fristline,lineSpaceSetting,alignmentStyleSetting,leading};
        paragraphStyle = CTParagraphStyleCreate(paragraphSettings, 4);
    }else{
        CTParagraphStyleSetting paragraphSettings[3] = {lineSpaceSetting,alignmentStyleSetting,leading};
        paragraphStyle = CTParagraphStyleCreate(paragraphSettings, 3);
    }
    
    CFRange textRange = CFRangeMake(0, text.length);
    
    CFMutableAttributedStringRef string = CFAttributedStringCreateMutable(kCFAllocatorDefault, text.length);
    CFAttributedStringReplaceString(string, CFRangeMake(0, 0), (CFStringRef)text);
    
    CFAttributedStringSetAttribute(string, textRange, kCTFontAttributeName, fontRef);
    CFAttributedStringSetAttribute(string, textRange, kCTParagraphStyleAttributeName, paragraphStyle);
    
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(string);
    
    CGSize textLabelSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter,
                                                                        CFRangeMake(0, text.length),
                                                                        NULL,
                                                                        maxSize,
                                                                        NULL);
    textLabelSize.height = textLabelSize.height+1;
    return textLabelSize;
    
}

- (UIImage *)captureView:(UIView *)aview
{
    UIView *capturedView=aview;
    
    UIGraphicsBeginImageContextWithOptions(capturedView.bounds.size, capturedView.opaque, 0.0);
    [capturedView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
}

@end
